package org.hughie.core;


import org.hughie.common.MConstant;
import org.hughie.common.SyncConfig;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;


public class DataSyncService {
    private static int threadCount = 4;
    private static final List<String> databases = new ArrayList<>();

    private static final Properties properties = new Properties();

    private static final Map<String, String> DB_CONFIG_MAP = new HashMap<>();


    public static void main(String[] args) {
        loadDatabaseConfigs();
        SwingUtilities.invokeLater(DataSyncService::createAndShowGUI);
    }

    private static void loadDatabaseConfigs() {
        try (FileInputStream fis = new FileInputStream(SyncConfig.getConfigFilePath())) {
            properties.load(fis);
            databases.clear();
            properties.forEach((key, value) -> {
                databases.add((String) key);
                DB_CONFIG_MAP.put((String) key, (String) value);
            });
            JOptionPane.showMessageDialog(null, "成功加载配置文件: " + SyncConfig.getConfigFilePath(), "INFO", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "无法加载配置文件: " + SyncConfig.getConfigFilePath(), "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("数据同步工具");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);

        JMenuBar menuBar = new JMenuBar();
        JMenu settingsMenu = new JMenu("系统设置");
        JMenuItem threadSettings = new JMenuItem("线程配置");
        JMenuItem configFilePathSettings = new JMenuItem("配置文件");
        JMenuItem aboutMenu = new JMenuItem("关于系统");

        threadSettings.addActionListener(e -> showThreadSettingsDialog(frame));
        configFilePathSettings.addActionListener(e -> showConfigFilePathDialog(frame));
        aboutMenu.addActionListener(e->showAboutDialog(frame));
        settingsMenu.add(threadSettings);
        settingsMenu.add(configFilePathSettings);
        settingsMenu.add(aboutMenu);
        menuBar.add(settingsMenu);

        frame.setJMenuBar(menuBar);


        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setLayout(new GridLayout(5, 2, 10, 10));

        panel.add(new JLabel("源数据库:"));
        JComboBox<String> sourceDbCombo = new JComboBox<>(databases.toArray(new String[0]));
        panel.add(sourceDbCombo);

        panel.add(new JLabel("目标数据库:"));
        JComboBox<String> targetDbCombo = new JComboBox<>(databases.toArray(new String[0]));
        panel.add(targetDbCombo);

        panel.add(new JLabel("表名:"));
        JTextField tableNameField = new JTextField(20);
        panel.add(tableNameField);

        panel.add(new JLabel("同步条件:"));
        JTextField conditionField = new JTextField(MConstant.CONDITION_1_1, 20);
        panel.add(conditionField);

        JButton syncButton = new JButton("同步数据");
        panel.add(syncButton);

        frame.add(panel);
        frame.setVisible(true);

        syncButton.addActionListener((ActionEvent e) -> {
            SyncConfig config = new SyncConfig();
            config.setSourceDb(DB_CONFIG_MAP.get((String) sourceDbCombo.getSelectedItem()));
            config.setTargetDb(DB_CONFIG_MAP.get((String) targetDbCombo.getSelectedItem()));
            config.setTableName(tableNameField.getText());
            config.setCondition(conditionField.getText());
            config.setThreadCount(threadCount);
            int confirm;
            // 检查是否是全表同步
            if (MConstant.CONDITION_1_1.equals(config.getCondition().trim())) {
                confirm = JOptionPane.showConfirmDialog(
                        frame,
                        "即将进行 全表同步！\n是否继续？",
                        "确认全表同步",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE
                );

            } else {
                confirm = JOptionPane.showConfirmDialog(
                        frame,
                        "即将进行 按条件同步！\n是否继续？",
                        "确认同步",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE
                );
            }
            if (confirm != JOptionPane.YES_OPTION) {
                return; // 用户取消操作
            }
            DataSyncEngine.syncData(frame, config);
        });
    }

    private static void showThreadSettingsDialog(JFrame parent) {
        JSpinner threadSpinner = new JSpinner(new SpinnerNumberModel(threadCount, 1, 20, 1));
        int result = JOptionPane.showConfirmDialog(parent, threadSpinner, "设置线程数", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            threadCount = (int) threadSpinner.getValue();
        }
    }

    private static void showConfigFilePathDialog(JFrame parent) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int result = fileChooser.showOpenDialog(parent);
        if (result == JFileChooser.APPROVE_OPTION) {
            SyncConfig.setConfigFilePath(fileChooser.getSelectedFile().getAbsolutePath());
            loadDatabaseConfigs();
            JOptionPane.showMessageDialog(parent, "配置文件路径已更新: " + SyncConfig.getConfigFilePath(), "信息", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private static void showAboutDialog(JFrame parent) {
        JOptionPane.showMessageDialog(parent, "数据同步工具\n版本: 1.0\n作者: 程浩宇\n目前支持MySQL、TiDB", "关于", JOptionPane.INFORMATION_MESSAGE);
    }
}
